//与登录注册先关【用户】
import { reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo, reqLogout } from "@/api";
import { SET_TOKEN, GET_TOKEN,RESET_TOKEN} from "@/utils/USER_TOKEN";
const state = {
    //存储验证码
    code: '',
    token: GET_TOKEN(),//服务器下发的token令牌,第一：服务器用来区分用户，第二:用户可以携带token找服务器查找用户信息
    userInfo: {}
};
const mutations = {
    GETCODE: (state, code) => {
        state.code = code;
    },
    LOGIN: (state, token) => {
        state.token = token;
    },
    SET_USERINFO: (state, userInfo) => {
        state.userInfo = userInfo;
    },
    RESET_USERINFO: (state) => {
        //清除token以及用户信息
        state.token = ""
        state.userInfo = {};
        //清除本地存储token
        RESET_TOKEN();

    }
}
const actions = {
    //获取验证码
    getCode: async ({ commit, state, dispatch }, phone) => {
        //发请求,获取验证码
        let result = await reqGetCode(phone);
        //工作的时候，获取验证码,向服务器发请求携带手机号
        //服务器接收到手机号【java、php】相应的插件，把验证码发送到用户手机上
        //目前接口没有这个功能【花钱|省钱】
        if (result.code == 200) {
            commit('GETCODE', result.data);
            return 'ok';
        } else {
            return Promise.reject();
        }
    }
    ,
    //注册用户
    userRegister: async ({ commit, state, dispatch }, user) => {
        //注册用户请求
        let result = await reqUserRegister(user);
        //返回成功与失败状态
        if (result.code == 200) {
            return 'ok';
        } else {
            return Promise.reject();
        }
    },
    //登录
    login: async ({ commit, state, dispatch }, data) => {
        //登录这里很重要***
        let result = await reqUserLogin(data);
        //result:当用户登录成功以后，服务器返回的结果[token:令牌]
        if (result.code == 200) {
            //vuex在存储token---并非持久化，一刷新token就没有
            commit("LOGIN", result.data.token);
            //本地存储：持久化存储token
            SET_TOKEN(result.data.token);
            return 'ok';
        } else {
            return Promise.reject(result.message);
        }
    },
    //获取用户信息
    getUserInfo: async ({ commit, state, dispatch }) => {
        //发请求获取用户信息
        let result = await reqUserInfo();
        if (result.code == 200) {
            commit('SET_USERINFO', result.data);
            return 'ok';
        }else{
            return Promise.reject();
        }
    },
    //退出登录
    logout: async ({ commit, state, dispatch }) => {
        //通知服务器清除token
        let result = await reqLogout();
        if (result.code == 200) {
            //清除state里面数据
            commit("RESET_USERINFO");
            return 'ok';
        } else {
            return Promise.reject();
        }
    }
};
const getters = {};

//默认暴露:小仓库对外暴露的是对象,默认暴露
export default {
    state,
    mutations,
    actions,
    getters
}